<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property string $id
 * @property string $group_id
 * @property string $group_ids
 * @property string $display_group_id
 * @property string $username
 * @property string $name
 * @property string $first_name
 * @property string $last_name
 * @property string $password
 * @property string $salt
 * @property string $email
 * @property string $avatar_path
 * @property string $join_date
 * @property string $activation_key
 */
class User extends CActiveRecord
{
	const AVATAR_PATH = 'upload/module_user/avatar/';
	public static function model($className=__CLASS__) {return parent::model($className);}
	public function tableName() {return '{{user}}';}
	public function rules()
	{
		// Define only rules for those attributes that will receive user inputs.
		return array(
			array('name, last_name, password, email, join_date', 'required'),
			array('group_id, display_group_id', 'length', 'max'=>10),
			array('group_ids, name, email', 'length', 'max'=>100),
			array('username, activation_key', 'length', 'max'=>60),
			array('first_name, last_name', 'length', 'max'=>50),
			array('password', 'length', 'max'=>64),
			array('salt', 'length', 'max'=>16),
			array('avatar_path', 'length', 'max'=>255),
			array('join_date', 'length', 'max'=>11),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, group_id, group_ids, display_group_id, username, name, first_name, last_name, password, salt, email, avatar_path, join_date, activation_key', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
			'metas'=>array(self::HAS_MANY, 'UserMeta', 'user_id'),
			'group'=>array(self::BELONGS_TO, 'UserGroup', 'group_id'),
			'facebook'=>array(self::HAS_ONE, 'UserFacebook', 'user_id'),
			'profile'=>array(self::HAS_ONE, 'UserProfile', 'user_id'),
		);
	}
	
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' 				=> Yii::t('user', 'ID'),
			'group' 			=> Yii::t('user', 'Nhóm thành viên'),
			'group_id' 			=> Yii::t('user', 'Nhóm chính'),
			'group_ids' 		=> Yii::t('user', 'Các nhóm phụ'),
			'display_group_id' 	=> Yii::t('user', 'Nhóm hiển thị'),
			'username' 			=> Yii::t('user', 'Tài khoản'),
			'name' 				=> Yii::t('user', 'Họ và tên'),
			'first_name'		=> Yii::t('user', 'Họ'),
			'last_name' 		=> Yii::t('user', 'Tên'),
			'password' 			=> Yii::t('user', 'Mật khẩu'),
			'salt' 				=> Yii::t('user', 'Salt'),
			'email' 			=> Yii::t('user', 'Email'),
			'avatar_path'		=> Yii::t('user', 'Avatar'),
			'join_date' 		=> Yii::t('user', 'Ngày tham gia'),
			'activation_key' 	=> Yii::t('user', 'Mã kích hoạt'),
		);
	}

	/**
	 * hoạt a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($criteria=NULL)
	{
		if($criteria===NULL) $criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,false);
		$criteria->compare('group_id',$this->group_id,false);
		$criteria->compare('group_ids',$this->group_ids,true);
		$criteria->compare('display_group_id',$this->display_group_id,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('first_name',$this->first_name,true);
		$criteria->compare('last_name',$this->last_name,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('activation_key',$this->activation_key,true);
		
		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
			'sort'=>array('defaultOrder'=>'id DESC'),
			'pagination'=>array('pageSize'=>Yii::app()->session->get('adminPageSize',25)),
		));
	}
	
	
/**** Password, Activation, Registration ****/
	
	/* Generate new password, encrypt it and set it to model's password
	Return: the RAW password */
	public function generatePassword()
	{
		$new_pass = substr(md5(time().sha1(uniqid())),3,10);
		$this->password = self::EncryptPassword($new_pass);
		return $new_pass;
	}
	
	/* Check if raw input password by user match encrypted password stored in database or not */
	public function checkPassword($input_password)
	{
		return $this->password == self::EncryptPassword($input_password);
	}
	
	// the "RAW" password input by user, like nghianghia / 12345678
	public static function EncryptPassword($string_password)
	{
		return md5(sha1($string_password).md5($string_password));
	}
	
	public function generateActivationKey()
	{
		$this->activation_key = sha1(uniqid());
	}	
	
	
	/**** METADATA ****/
	public function setMeta($key, $value)
	{
		// serialize value before saving
		$value = CJSON::encode($value);
		
		// check if this [user_id, key] exist in database
		$criteria = new CDbCriteria;
		$criteria->compare('user_id',$this->id);
		$criteria->compare('meta_key',$key);
		
		$meta = UserMeta::model()->find($criteria);
		if($meta===NULL)
		{
			$new_meta = new UserMeta;
			$new_meta->user_id = $this->id;
			$new_meta->meta_key = $key;
			$new_meta->meta_value = $value;
			$new_meta->save();
			return true;
		} 
		else
		{
			$meta->meta_value = $value;
			$meta->save();
			return true;
		}
		return false;
	}
	
	/**
	 * Return value for a key stored for this user in UserMeta table
	 * TODO: store & query from cache
	 * 
	 * @param string $key 
	 * @param string $default 
	 * @return void
	 * @author QuangNghia
	 */
	public function getMeta($key,$default=NULL)
	{
		$criteria = new CDbCriteria;
		$criteria->compare('user_id', $this->id);
		$criteria->compare('meta_key',$key);
		$meta = UserMeta::model()->find($criteria);
		if($meta===NULL)
		{
			return $default;
		}
		else
		{
			return CJSON::decode($meta->meta_value);
		}
	}
	
	/**
	* @param string $file the CUploadedFile
	**/
	public function setAvatar($file)
	{
		// create a unique name for the uploaded file.
		$saveFileName = NFile::createPath(self::AVATAR_PATH) . "_{$this->user_id}." . strtolower($file->getExtensionName());

		// add _t to file name to create thumb file.
		$saveThumbFileName = str_replace('.','_t.',$saveFileName);

		//try to save
		if($file->saveAs($saveFileName))
		{
			// create a crop thumbnail at 128px
			// TODO: change to NImage resizeAndCrop function
			NImage::resizeAndCrop($saveFileName, $saveThumbFileName, 128);
			
			// delete previous avatar
			@unlink($avatar);
			@unlink(str_replace('_t.','.',$avatar));
						
			// save new avatar thumbnail name to database
			$this->avatar_path = $saveThumbFileName;
			
			return true;
		}
		return false;
	}
	
	public function getAvatar($size='default')
	{
		return NHtml::image($this->avatar_path, $this->name, array('width'=>'50px','height'=>'50px','style'=>'display:block;','class'=>'shadow'));
	}

	public function getAccountUrl()
	{
		return Yii::app()->controller->createAbsoluteUrl('/user/account',array('username'=>$this->username));
	}

	public function afterDelete()
	{
		parent::afterDelete();
		
		// Delete avatar image file
		@unlink($this->avatar_path);
		@unlink(str_replace('_t.','.',$this->avatar_path));
		
		// Delete extra meta data of this user
		foreach ($this->metas as $meta) {
			$meta->delete();
		}
		
		// Delete facebook account
		if($this->facebook!==NULL) $this->facebook->delete();
		
		// Delete profile
		if($this->profile!==NULL) $this->profile->delete();
	}
}